package com.by.basicweb.config.undertow;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.by.toolkit.consts.DatePatternConst;
import io.undertow.attribute.ExchangeAttribute;
import io.undertow.attribute.ExchangeAttributeBuilder;
import io.undertow.attribute.ReadOnlyAttributeException;
import io.undertow.server.HttpServerExchange;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

public class UTCTimeAttribute implements ExchangeAttribute {

    public static final String NAME = "UTC Time";

    public static final String UTC_TIME = "%{utcTime}";

    public static final ExchangeAttribute INSTANCE = new UTCTimeAttribute();

    @Override
    public String readAttribute(HttpServerExchange httpServerExchange) {
        return LocalDateTimeUtil.format(LocalDateTime.now(ZoneOffset.UTC), DatePatternConst.LOG_TIME_PATTERN);
    }

    @Override
    public void writeAttribute(HttpServerExchange httpServerExchange, String s) throws ReadOnlyAttributeException {
        throw new ReadOnlyAttributeException(NAME, s);
    }

    public static final class Builder implements ExchangeAttributeBuilder {

        @Override
        public String name() {
            return NAME;
        }

        @Override
        public ExchangeAttribute build(String token) {
            if (UTC_TIME.equals(token)) {
                return UTCTimeAttribute.INSTANCE;
            }
            return null;
        }

        @Override
        public int priority() {
            return 0;
        }
    }

}
